import { CoolController, BaseController } from '@cool-midway/core';
import { GoodsInfoEntity } from '../../entity/info';
import { GoodsInfoService } from '../../service/info';
import { GoodsTypeEntity } from '../../entity/type';
import { Body, Inject, Post } from '@midwayjs/core';
/**
 * 商品信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: GoodsInfoEntity,
  service: GoodsInfoService,
  pageQueryOp: {
    keyWordLikeFields: ['a.title', 'a.subTitle'],
    select: ['a.*', 'b.name as typeName'],
    fieldEq: ['a.status', 'a.typeId'],
    addOrderBy: {
      sortNum: 'desc',
    },
    where: ctx => {
      const { attribute } = ctx.request.body;
      const conditions = [

      ];

      // 处理多选属性查询
      if (attribute) {
        const attributes = attribute.toString().split(',');
        const attrConditions = attributes.map(attr => {
          return [`a.attribute LIKE :attr${attr}`, { [`attr${attr}`]: `%${attr}%` }];
        });
        if (attrConditions.length > 0) {
          conditions.push(['(' + attrConditions.map(([sql]) => sql).join(' OR ') + ')', 
            attrConditions.reduce((params, [_, param]) => ({ ...params, ...param }), {})
          ]);
        }
      }

      return conditions;
    },
    join: [
      {
        entity: GoodsTypeEntity,
        alias: 'b',
        condition: 'a.typeId = b.id',
      },
    ],
  },
})
export class AdminGoodsInfoController extends BaseController {
  @Inject()
  goodsInfoService: GoodsInfoService;

  @Post('/getGoodsFromFixture')
  async getGoodsFromFixture(@Body() params: any) {
    return this.goodsInfoService.getGoodsFromFixture(params);
  }
}
